package com.cnblogs.leizia.crm.settings.web.controller;

import com.cnblogs.leizia.crm.commen.RequestUri;
import com.cnblogs.leizia.crm.commen.Result;
import com.cnblogs.leizia.crm.settings.domain.User;
import com.cnblogs.leizia.crm.settings.service.UserService;
import com.cnblogs.leizia.crm.settings.service.impl.UserServiceImpl;
import com.cnblogs.leizia.crm.utils.MD5Util;
import com.cnblogs.leizia.crm.utils.PrintJson;
import com.cnblogs.leizia.crm.utils.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author leizi
 * @create 2021-02-13 17:50
 */
public class UserController extends HttpServlet {

    /**
     * 代理对象（解耦）
     */
    private UserService userService = (UserService) ServiceFactory.getService(new UserServiceImpl());

    /**
     * 请求分发
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        // 用户登录
        if (RequestUri.USER_LOGIN.getUriPath().equals(req.getServletPath())) {
            login(req, resp);
        }
    }

    /**
     * 登录
     */
    private Result login(HttpServletRequest req, HttpServletResponse resp) {
        String loginAct = req.getParameter("loginAct");
        // 密码转换为密文
        String loginPwd = MD5Util.getMD5(req.getParameter("loginPwd"));
        String remoteAddr = req.getRemoteAddr();
        User user = null;

        try {
            user = userService.login(loginAct, loginPwd, remoteAddr);
            // 用户信息保存到session域中
            req.getSession().setAttribute("user",user);
            // 返回成功
            PrintJson.printJsonFlag(resp,true);

            return Result.successResult();
        } catch (Exception e) {
            e.printStackTrace();
            // 返回失败信息
            PrintJson.printJsonObj(resp, Result.errorResult(e.getMessage()));
        }
        return null;
    }
}
